package com.tiduyun.data.exchange.controller;

import java.io.Reader;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.io.IOUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import com.tiduyun.data.exchange.service.GxVehicleDataAdapterService;
import com.tiduyun.data.exchange.util.JSONUtils;

import lombok.extern.slf4j.Slf4j;

@RestController
@RequestMapping("/debug/openapi/gxVehicle")
@Slf4j
public class GxVehicleDataExchangeDebugController {

    @Value("${td-data.debug.enable}")
    private boolean debugEnable = false;

    @Autowired
    @Qualifier("gxVehicleDataAdapterServiceImpl")
    private GxVehicleDataAdapterService gxVehicleDataAdapterService;

    @RequestMapping(path = "/getVehicleInfo", method = RequestMethod.POST)
    public Object getVehicleInfo(HttpServletRequest request, Reader bodyReader) {
        if (!debugEnable) {
            return null;
        }
        Map<String, Object> params = loadBodyParams(bodyReader);
        return gxVehicleDataAdapterService.getVehicleInfo(params);
    }

    @RequestMapping(path = "/checkVehicleInvoice", method = RequestMethod.POST)
    public Object checkVehicleInvoice(HttpServletRequest request, Reader bodyReader) {
        if (!debugEnable) {
            return null;
        }
        Map<String, Object> params = loadBodyParams(bodyReader);
        return gxVehicleDataAdapterService.checkVehicleInvoice(params);
    }

    private Map<String, Object> loadBodyParams(Reader bodyReader) {
        String body = null;
        try {
            body = IOUtils.toString(bodyReader);
            return JSONUtils.parseMap(body);
        } catch (Exception e) {
            log.error("Read body failed", e);
            return null;
        }
    }

}
